<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-tagfill"></i> 赛事管理</el-breadcrumb-item>
                <el-breadcrumb-item>赛事编辑</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column label="比赛名称" prop="cname" align="center"/>
            <el-table-column label="裁判" prop="headJudgeName" align="center"/>
            <el-table-column label="比赛预估耗时" prop="timeNeed" align="center"/>
            <el-table-column label="比赛规则" prop="crule" align="center"/>
            <el-table-column align="center">
            <template #header>
                <el-input v-model="search" size="small" placeholder="请输入比赛名称">
                    <template #append>
                        <el-button @click="handleSearch()" icon="el-icon-search">
                            搜索
                        </el-button>
                    </template>
                </el-input>
            </template>
            <template #default="scope">
                <el-button size="small" type="primary" icon="el-icon-edit"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="small" type="danger" icon="el-icon-delete"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
            </el-table-column>
            </el-table>
        <!-- 编辑弹出框 -->
        <el-dialog v-model="dialogFormVisible" title="项目" center draggable>
            <el-card shadow="hover">
                <el-form :model="compForm" :label-width="formLabelWidth">
                <el-form-item label="比赛名称" >
                    <el-input v-model="compForm.cname" disabled />
                </el-form-item>
                <el-form-item label="裁判">
                    <el-select v-model="compForm.headJudgeName" filterable remote 
                        placeholder="请输入关键词" :remote-method="getRecommendRefereesList"
                        :loading="loading">
                        <el-option v-for="item in recommendRefereesList"
                            :key="item.value"
                            :label="item.value+'-'+item.label"
                            :value="item.value+'-'+item.label"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="比赛预估耗时">
                    <el-input v-model="compForm.timeNeed"  />
                </el-form-item>
                <el-form-item label="比赛规则">
                    <el-input v-model="compForm.crule" autocomplete="off" />
                </el-form-item>
                </el-form>
            </el-card>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="danger"  @click="saveEdit()">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 分页 -->
        <el-card>
            <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize"
                background="true"
                layout="total, prev, pager, next, jumper"
                :total="parseInt(totalNum)" 
                :page-sizes="pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
    </div>
  
</template>

<script>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from 'vuex';
import { map } from 'lodash';
export default{
    setup(){
        const store  = useStore();

        
        

        let dialogFormVisible = ref(false)
        const formLabelWidth = '140px'
        const compForm = reactive({
            cname: '',
            headJudgeName:"",
            timeNeed:"",
            crule:"",
        });
       
        const handleEdit = (index, row) => {
            dialogFormVisible.value = true;
            compForm.cname = row.cname;
            const tepJudge = remoteReferees.filter((item) => {
                        // console.log("item",item)
                        return item.label.toString().search(row.headJudgeName)>-1 ||
                            item.value.toString().search(row.headJudgeName)>-1
                    })[0];
            compForm.headJudgeName = tepJudge.value+"-"+tepJudge.label;
            console.log("compForm.headJudgeName",compForm.headJudgeName)
            compForm.timeNeed = row.timeNeed;
            compForm.crule = row.crule;
            editIndex.value = index;
        }
        const handleDelete = (index, row) => {
            ElMessageBox.confirm("确定要删除吗","提示",{
                type:"warning",
            }).then(()=>{
                store.dispatch("DeleteCompetition",row.cname)
                .then((result)=>{
                    // console.log("res is ",result)
                    if(result == "ok"){
                        ElMessage({
                            type:"success",
                            message:"删除成功",
                            center:true,
                        })
                        tableData.splice(index,1)
                    }else{
                        ElMessage({
                            type:"error",
                            message:"删除失败,该数据已被使用",
                            center:true,
                        })
                    }
                })
                .catch("error",(err)=>{
                    console.log("删除异常 is ",err)
                })
            }).catch((err)=>{
                console.log("删除异常 ",err)
            })
            
        }

        /* 远程搜索裁判 */
        const loading = ref(false);
        const remoteReferees = reactive([]);
        let recommendRefereesList = reactive([]);
        const getRecommendRefereesList = (query)=>{
            // console.log("处理后的远端数据为 ",remoteReferees);
            // console.log("@@搜索的关键词为 ",query);
            if(query.length>0){
                loading.value = true;
                setTimeout(() => {
                    loading.value = false
                    recommendRefereesList.splice(0,recommendRefereesList.length,...remoteReferees.filter((item) => {
                        // console.log("item",item)
                        return item.label.toString().search(query)>-1 ||
                            item.value.toString().search(query)>-1
                    })) 
                    // console.log("@@推荐的裁判列表为 ",recommendRefereesList)
                }, 200)
            }else{
                recommendRefereesList.splice(0,recommendRefereesList.length,...remoteReferees);
            }
        };

        let editIndex = ref(-1);
        const saveEdit = ()=>{
            console.log("需要保存的编辑项目@@@",{
                    cname:compForm.cname,
                    crule:compForm.crule,
                    headJudge:compForm.headJudgeName.split("-")[0],
                    timeNeed:compForm.timeNeed,
                })
            ElMessageBox.confirm("确定要保存吗","提示",{
                type:"warning",
                center:true,
            }).then(()=>{
                store.dispatch("UpdateCompetition",{
                    cname:compForm.cname,
                    crule:compForm.crule,
                    headJudge:compForm.headJudgeName.split("-")[0],
                    timeNeed:compForm.timeNeed,
                }).then(res=>{
                    if(res.code === 200){
                        ElMessage({
                            type:"success",
                            message:"更新成功",
                            center:true,
                        })
                        getCompetitionList();
                    }else{
                        ElMessage({
                            type:"error",
                            message:"更新失败 "+res.message,
                            center:true,
                        })
                    }
                }).catch(err=>{
                    console.log("更新异常， ",err)
                })
                dialogFormVisible.value = false
            }).catch(()=>{
                ElMessage.error("保存失败");
            })
        }
        
        let tableData = reactive([]);
        const getCompetitionList = ()=>{
            store.dispatch("CompetitionList",{
                PageNum:currentPage.value,
                PageSize: pageSize.value,
            })
            .then((res)=>{
                if(res.code===200){
                    console.log(" CompetitionList ###",res)
                    totalNum.value = res.message;
                    tableData.splice(0, tableData.length, ...res.obj);
                    // console.log("比赛列表",tableData)
                }
            })
            .catch(err=>{
                console.log("报错为",err)
            })
        }
        const search = ref('');
        const handleSearch = ()=>{
            // console.log("搜索内容",search)
            store.dispatch("SearchCompetition",search.value)
            .then((res)=>{
                if(res.code===200){
                    tableData.splice(0,tableData.length, ...res.obj);
                    // console.log("比赛列表",tableData);   
                }else{
                    ElMessage({
                        type:"error",
                        message:res.message,
                        center:true,
                    })
                }
            })
            .catch(err=>{
                console.log("报错为",err)
            })
        }

        onMounted(()=>{
            getCompetitionList();
            store.dispatch("RefereeList").then(res=>{
                if(res.code===200){
                    remoteReferees.splice(0,remoteReferees.length,...map(res.obj,(item)=>{
                        return {
                        value:item.jid,
                        label:item.name
                        }
                    }))
                // console.log("remoteReferees ",remoteReferees)
                }else{
                    console.log("获取所有裁判失败",res.message)
                }
            }).catch(err=>{
                console.log("查询裁判结果出现异常 ",err);
            });
        })
         //分页
        let currentPage = ref(1);
        let pageSize = ref(5);
        let totalNum = ref(14);//总条数除以每页显示条数5
        const handleSizeChange = (val) => {
            // console.log(`${val} items per page`)
        }
        const handleCurrentChange = (val) => {
            // console.log(`current page: ${val}`)
            getCompetitionList();
        }
        return {
            compForm,
            dialogFormVisible,
            formLabelWidth,
            search,
            handleEdit,
            handleDelete,
            saveEdit,
            tableData,
            getCompetitionList,
            handleSearch,
            //查询裁判
            loading,
            getRecommendRefereesList,
            recommendRefereesList,
            remoteReferees,
            //分页
            currentPage,
            pageSize,
            totalNum,
            handleSizeChange,
            handleCurrentChange,
        }
    }
}
</script>
